<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Api\Controller;
use App\Models\Picture;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PictureController extends Controller
{

  //列表
  public function index(Request $request)
  {
    $cates = Picture::getList($request);
    return $this->success($cates);
  }

  // 详情
  public function detail($id)
  {
    $cateInfo = Picture::getInfo($id);
    return $this->success($cateInfo);
  }

  // 新增
  public function add(Request $request)
  {
    $data = $request->all();
    $rule = [
      'img'     => 'required',
    ];
    $message = [
      'img.required'       => '图片不能为空',
    ];
    $validated = $this->validator($data, $rule, $message);
    if (is_bool($validated)) {
      $parentid = $request->parentid;
      $insertData = [
        'img' => $request->img ?? '',
        'en_img' => $request->en_img ?? '',
        'status' => $request->status,
        'sort' => $request->sort ?? 0,
        'created_at' => date('Y-m-d H:i:s'),
        'updated_at' => date('Y-m-d H:i:s'),
      ];
      $result = DB::table('pictures')->insert($insertData);
      return $this->success();
    } else {
      return $validated;
    }
  }

  // 修改
  public function update(Request $request)
  {
    $cateInfo = DB::table('pictures')->where('id', $request->id)->first();
    if ($cateInfo && $cateInfo->id) {
      $parentid = $request->parentid;
      $updateData = [
        'img' => $request->img ?? $cateInfo->img,
        'en_img' => $request->en_img ?? $cateInfo->en_img,
        'status' => $request->status ?? $cateInfo->status,
        'sort' => $request->sort ?? $cateInfo->sort,
        'updated_at' => date('Y-m-d H:i:s'),
      ];
      $result = DB::table('pictures')->where('id', $request->id)->update($updateData);
      if ($result) {
        return $this->success();
      }
      return $this->failed('修改失败');
    } else {
      return $this->failed('图片不存在');
    }
  }

  // 删除
  public function delete($id)
  {
    $result = Picture::del($id);
    if ($result) {
      return $this->success();
    }
    return $this->failed('删除失败');
  }
}
